package org.lq.rbac.service.impl;


import org.lq.rbac.dto.MenuDTO;
import org.lq.rbac.dto.util.Populate;
import org.lq.rbac.mapper.MenuPoMapper;
import org.lq.rbac.po.MenuPo;
import org.lq.rbac.po.MenuPoExample;
import org.lq.rbac.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuPoMapper menuPoMapper;

    @Override
    public List<MenuDTO> list(Integer super_id)throws Exception{

        return list(super_id,false);
    }
    private List<MenuDTO> list(Integer super_id,boolean recursion) throws Exception {

        MenuPoExample example=new MenuPoExample();
        MenuPoExample.Criteria criteria = example.createCriteria();
        criteria.andSuperIdEqualTo(super_id);

        List<MenuPo> menuPoList = menuPoMapper.selectByExample(example);

        if (menuPoList==null && menuPoList.size()==0) return null;

        List<MenuDTO> menuDTOList=new LinkedList<>();
        for (MenuPo menuPo:menuPoList){
            MenuDTO menuDTO=new MenuDTO();

            Populate.po2dto(menuPo,menuDTO);

            menuDTOList.add(menuDTO);

            if (recursion){
                Integer id = menuDTO.getId();
                List<MenuDTO> children = list(id, true);
                menuDTO.setChildren(children);
            }
        }
        return menuDTOList;
    }
    @Override
    public List<MenuDTO> allMenus() throws Exception {
        return list(0,true);
    }
}
